/**
 * 注册校验
 * 
 * @authors supmain (mtingfeng@gmail.com)
 * @date 2014-09-05 11:10:42
 * @update 2014-09-05 11:10:42
 * @for register.jsp
 * @version $Id$
 */
var BSTYUN = BSTYUN || {};
BSTYUN.check = {
	// IE6判定
	isIE6 : window.VBArray && !window.XMLHttpRequest,
	// 判断是否为中英文，数字，下划线，减号
	isNick : function(str) {
		var nickReg = /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/;
		return nickReg.test(str);
	},
	// 判断邮箱
	isEmail : function(str) {
		var emailReg = /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i;
		return emailReg.test(str);
	},
	// 判断URL
	isUrl : function(str) {
		var urlReg = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
		return urlReg.test(str);
	},
	// 判断数字
	isNum : function(str) {
		var numReg = /^[0-9]\d*$/;
		return numReg.test(str);
	}
};
BSTYUN.register = {
	$inputs : null,
	flag : {
		email : false,
		psd : false,
		cfm_psd : false,
		phone : false,
		vftn_code : false,
		picode : false
	},
	_timer : null,/* 全局定时器 */
	init : function() {
		var that = this;
		/* 获取input元素 */
		that.$inputs = $('.input_box').find('input');
		/* 检测信息 */
		that.checkInfor();
		/*获取邮箱验证码*/
		that.sendEmailCode()
		/* 提交注册 */
		that.submitRegister();
		/* 图片验证码替换 */
		that.changePicCode();
	},
	checkInfor : function() {
		var that = this;
		/* 获取焦点，清空错误信息 */
		that.$inputs
				.on('focus', function(event) {
					that.clearErrorMsg($(this));
					/* 失去焦点，检测信息正确性 */
				})
				.on(
						'blur',
						function(event) {
							var $this = $(this), typename = $this.attr('name'), val = $
									.trim($this.val());
							/* 输入内容为空，则提示不能为空 */
							if (val == '' || val.length == 0) {
								that.addErrorMsg($this, '不能为空');
								return false;
							}
							if (typename == 'email') {
								if (!BSTYUN.check.isEmail(val)) {
									that.addErrorMsg($this, '邮箱格式不正确');
								} else {
									/* ajax判断用户名是否存在 */
									$.ajax({
												type : "post",
												url : "/user/email?random="
														+ Math.random(),
												// url:
												// "text.txt?random="+Math.random(),
												data : {
													userEmail : val
												},
												async : false,
												// dataType: "json",
												success : function(data) {
													if (data == false) {
														that.addErrorMsg($this,'该用户已存在，请<a href="/user/login">登录</a>');
													} else {
														that.clearErrorMsg($this);
													}
												}
											});
								}
							}else if (typename == 'psd') {
								var $cfm_psd = $this.parents('.input_box')
										.next().find('#cfm_psd'), cfm_psd_val = $
										.trim($cfm_psd.val());
								if (val.length < 6 || val.length > 20) {
									that.addErrorMsg($this, '长度必须在6-20之间');
								}
								if (cfm_psd_val != ''
										|| cfm_psd_val.length != 0) {
									if (val != cfm_psd_val) {
										that.addErrorMsg($cfm_psd, '两次输入密码不一致');
									} else {
										that.clearErrorMsg($cfm_psd);
									}
									;
								}
								;
							} else if (typename == 'cfm_psd') {
								var psd = $.trim($this.parents('.input_box')
										.prev().find('#psd').val());
								if (val != psd) {
									that.addErrorMsg($this, '两次输入密码不一致');
								}
								;
							} else if (typename == 'picode') {

							}
							;
						});
        /*判断邮箱，是否可以发送邮件*/
        that.$inputs.filter("[name='email']").on('keyup', function(event) {
            var $send = $('#getvftn_code'),
            	$this = $(this),
                val = $.trim($this.val());
            //if(BSTYUN.register._timer != null){return false;};
            if (!BSTYUN.check.isEmail(val)) {
                $send.addClass('disabled');
            }else{
                $send.removeClass('disabled');
                /*判断邮箱，是否已经被注册*/
				$.ajax({
							type : "post",
							url : "/user/email?random="
									+ Math.random(),
							// url:
							// "text.txt?random="+Math.random(),
							data : {
								userEmail : val
							},
							async : false,
							// dataType: "json",
							success : function(data) {
								if (data == false) {
									that.addErrorMsg($this,'该用户已存在，请<a href="/user/login">登录</a>');
									 $send.addClass("disabled");
								} else {
									that.clearErrorMsg($this);
									$send.removeClass("disabled");
								}
							}
						});
            }
        });
	},
    sendEmailCode: function(argument) {
        var that = this,
            $send = $('#getvftn_code'),
            $email = that.$inputs.eq(0),
            val = null;
            $send.on('click', function(event) {
                var $this = $(this);
                if (!$this.hasClass('disabled')) {
//                    $this.addClass('disabled');
                    val = $.trim($email.val());
                    /*发送ajax请求短信验证码*/
                    $.ajax({
                        type: "post",
                        url: "/user/sendEmail?random="+Math.random(),
                        //url: "text.txt?random="+Math.random(),
                        data: {email:val},
                        error: function(request){
                        	that.addErrorMsg($email,'邮件发送失败，请重试');
                        },
                        success: function(data){
                            if(data==true){
                            	that.addTipMsg($email,'邮件发送成功');
                                return true;
                            }else{
                            	that.addErrorMsg($email,'邮件发送失败，请重试');
                            	return false;
                            }
                        }
                    });
                }else{
                   /*禁止状态，不能点击*/
                   return false;
                };
            });
    },
	submitRegister : function() {
		var that = this, $submit = $("#go2register");
		$submit.on('click', function(event) {
			var flag = that.flag, data = {};
			$.each(that.$inputs, function(index, val) {
				$(this).trigger('blur');
			});
			if (flag.email != false && vftn_code !=false &&flag.psd != false
					&& flag.cfm_psd != false && flag.picode != false) {
				data.email = $.trim(that.$inputs.eq(0).val()), 
				data.emailCode = $.trim(that.$inputs.eq(1).val()), 
				data.psd = $.trim(that.$inputs.eq(2).val()), 
				data.cfm_psd = $.trim(that.$inputs.eq(3).val()), 
				data.picode = $.trim(that.$inputs.eq(4).val());
				$.ajax({
					type : "POST",
					url : "/user?random=" + Math.random(),
					data : data,
					async : false,
					error : function(request) {
						BSTYUN.dialog.ok('服务器繁忙，请稍后尝试')
						return false;
					},
					success : function(data) {
						var emailCode = data.emailCode;
						var imgSuccess = data.imgSuccess;
						var saveSuccess = data.saveSuccess;
						if(!emailCode){
							that.addErrorMsg(that.$inputs
									.filter("[name='vftn_code']"), '验证码错误');
						}else{
							if (imgSuccess == false && saveSuccess == "") {
								that.addErrorMsg(that.$inputs.filter("[name='picode']"), '验证码错误');
								return false;
							} else {
								if (saveSuccess == true) {
									window.location.href = "/user/userCenter"
								}
							}
						}
						

					}
				});
			}
			;
			return false;
		});
	},
	changePicCode : function() {
		var $change = $("#changeImgCode"), $img = $change.prev();
		$change.on('click', function(event) {
			$img.attr('src', '/image/code?random=' + Math.random());
		});
	},
	/* 清空$this的错误提示信息 */
	clearErrorMsg : function($this) {
		var $this = $this, that = this, typename = $this.attr('name');
		if (typename == 'email') {
			that.flag.email = true;
			$this.parent().next().children('.error_msg').remove();
		}else if(typename == 'vftn_code'){
			that.flag.vftn_code = true;
            $this.next().remove();
		} else if (typename == 'psd') {
			that.flag.psd = true;
			$this.parent().next().children('.error_msg').remove();
		} else if (typename == 'cfm_psd') {
			that.flag.cfm_psd = true;
			$this.parent().next().children('.error_msg').remove();
		} else if (typename == 'picode') {
			that.flag.picode = true;
			$this.parent().next().html('&nbsp;');
		}
		;
	},
	/* 显示错误信息 */
	addErrorMsg : function($this, msg) {
		var $this = $this, that = this, typename = $this.attr('name');
		if (typename == 'email') {
			that.flag.email = false;
			$this.parent().next().html('<span class="error_msg">' + msg + '</span>');
		} else if(typename == 'vftn_code'){
			that.flag.vftn_code = false;
	           if($this.next('.error_msg').size() != 0){
	               $this.next('.error_msg').html(msg);
	           }else{
	               $this.after('<span class="error_msg">'+msg+'</span>');
	           }
		}else if (typename == 'psd') {
			that.flag.psd = false;
			$this.parent().next().html('<span class="error_msg">' + msg + '</span>');
		} else if (typename == 'cfm_psd') {
			that.flag.cfm_psd = false;
			$this.parent().next().html('<span class="error_msg">' + msg + '</span>');
		} else if (typename == 'picode') {
			that.flag.picode = false;
			$this.parent().next().html('<span class="error_msg">' + msg + '</span>');
		}
		;
	},
	/* 显示提示信息 */
	addTipMsg : function($this, msg) {
		var $this = $this, that = this, typename = $this.attr('name'), $next = $this
				.parent().next();
		if (typename == 'email') {
			that.flag.email = false;
			$next.html('<span class="tip_msg">' + msg + '</span>');
			$next.children('.tip_msg').delay(2000).fadeOut(2000, function() {
				$(this).remove();
			});
		}
	}
}
$(function() {
	BSTYUN.register.init();
});

/**
 * 打开百顺通云服务协议
 */
function openDeal() {
	var openUrl = "/user/openBstDeal";// 弹出窗口的url
	window
			.open(
					openUrl,
					'_blank',
					'width='
							+ (window.screen.availWidth - 10)
							+ ',height='
							+ (window.screen.availHeight - 30)
							+ ',top=0,left=0,toolbar=yes,menubar=yes,scrollbars=yes, resizable=yes,location=yes, status=yes,channelmode=yes');
}
